<template>
  <div class="chart-container">
    <div ref="chart" class="chart-content"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'BarChart',
  props: {
    chartData: {
      type: Object,
      default: () => ({}),
    },
    chartOptions: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      chart: null,
      observer: null,
    }
  },
  mounted() {
    this.initChart()
    this.initResizeObserver()
  },
  methods: {
    initChart() {
      if (this.chart) {
        this.chart.dispose()
      }
      this.chart = echarts.init(this.$refs.chart)

      const option = {
        backgroundColor: 'transparent',
        title: {
          text: '柱状图示例',
          textStyle: {
            color: '#fff',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
          axisLine: {
            lineStyle: {
              color: '#fff',
            },
          },
          axisLabel: {
            color: '#fff',
          },
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#fff',
            },
          },
          axisLabel: {
            color: '#fff',
          },
        },
        series: [
          {
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.1)',
            },
            itemStyle: {
              color: 'rgba(255, 255, 255, 0.8)',
            },
          },
        ],
      }

      this.chart.setOption({ ...option, ...this.chartOptions })
    },
    initResizeObserver() {
      this.observer = new ResizeObserver(() => {
        if (this.chart) {
          this.chart.resize()
        }
      })
      this.observer.observe(this.$refs.chart)
    },
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
    if (this.observer) {
      this.observer.disconnect()
    }
  },
  watch: {
    chartData: {
      handler(newValue) {
        if (this.chart && newValue) {
          this.chart.setOption(newValue)
        }
      },
      deep: true,
    },
  },
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  padding: 10px;
  background: transparent;
  position: relative;
}

.chart-content {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
</style> 